import datetime
import os
import threading
import time

import run_sw_cmd
from TFTPServer import TFTPServer
from send_email import Email


def run_cmd():
    # 循环执行各交换机备份指令
    hosts = run_sw_cmd.get_devices_info()
    # get hosts
    global status
    status = 1
    try:
        for i in hosts:
            device_type, commands = run_sw_cmd.get_cmd_info(i['cmd'])
            # get device_type and cmds
            task = threading.Thread(target=run_sw_cmd.run_cmd, args=(i, commands, device_type))
            threads.append(task)
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        run_sw_cmd.show_info('All done.')
    except TypeError as e:
        run_sw_cmd.show_info('Please check the error.')


if __name__ == '__main__':
    LogDay = time.strftime('%m.%d')
    now = datetime.datetime.now()
    now_year = str(now.year)
    threads = []
    basedir = 'E:/工作/01日常及运维工作/配置备份'

    # 创建备份文件
    backupdir = os.path.join(basedir, now_year, LogDay)
    if not os.path.exists(os.path.join(basedir, now_year)):
        os.makedirs(os.path.join(basedir, now_year))

    if not os.path.exists(backupdir):
        os.makedirs(backupdir)

    # 启动TFTP服务端
    server = TFTPServer(backupdir)
    tftp_task = threading.Thread(target=server.run, daemon=True)
    cmd_stask = threading.Thread(target=run_cmd)
    tftp_task.start()
    cmd_stask.start()
    # 定义邮件内容
    body = '网络设备已完成配置备份，请核实确认。脚本发送请勿回复。'
    # "接收方的邮箱", "邮件标题", "邮件内容", "报告路径"
    Email("网络设备配置备份", body=body)
    print('邮件发送成功~！')
